<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            .carousel {
                width: 940px;
                height: 423px;
                border: 1px solid red;
                overflow: hidden;
                position: relative;
            }
            .carousel > img {
                position: absolute;
            }
            .img1 {
                left: 0;
            }
            .img2 {
                left: 940px;
            }
        </style>
    </head>
    <body>
        <div class="carousel">
            <img class="img1" src="../images/img1.jpg" alt="" />
            <img class="img2" src="../images/img2.jpg" alt="" />
        </div>
        <script src="../js/jquery-1.12.4.min.js"></script>
        <script>
            let ary = [
                "../images/img1.jpg",
                "../images/img2.jpg",
                "../images/img3.jpg",
                "../images/img4.jpg",
            ];
            let index = 0;
            setInterval(function () {
                moveImg();
            }, 2000);
            function moveImg() {
                $(".carousel>img").each(function () {
                    console.log($(this).position().left);
                    if ($(this).position().left == 0) {
                        $(this).animate(
                            {
                                left: -940,
                            },
                            500
                        );
                    } else {
                        index++;
                        if (index >= ary.length) {
                            index = 0;
                        }
                        $(this).css("left", 940);
                        $(this).attr("src", ary[index]);
                        $(this).animate(
                            {
                                left: 0,
                            },
                            500
                        );
                    }
                });
            }
        </script>
    </body>
</html>
